/**
 * MCP SSH工具 - 前端应用逻辑
 */

class SSHManager {
    constructor() {
        this.currentServer = null;
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadServers();
    }

    bindEvents() {
        // 添加服务器按钮
        document.getElementById('addServerBtn').addEventListener('click', () => {
            this.showAddServerModal();
        });

        // 模态对话框事件
        // 移除关闭按钮的自动关闭功能
        // document.getElementById('closeModalBtn').addEventListener('click', () => {
        //     this.hideAddServerModal();
        // });

        document.getElementById('cancelAddBtn').addEventListener('click', () => {
            this.hideAddServerModal();
        });

        // 添加服务器表单
        document.getElementById('addServerForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.addServer();
        });

        // 认证方式切换
        document.querySelectorAll('input[name="authType"]').forEach(radio => {
            radio.addEventListener('change', (e) => {
                this.toggleAuthFields(e.target.value);
            });
        });

        // 命令执行
        document.getElementById('executeBtn').addEventListener('click', () => {
            this.executeCommand();
        });

        // 测试连接
        document.getElementById('testConnectionBtn').addEventListener('click', () => {
            this.testConnection();
        });

        // 清空输出
        document.getElementById('clearOutputBtn').addEventListener('click', () => {
            this.clearOutput();
        });

        // 移除点击对话框外部自动关闭功能
        // window.addEventListener('click', (e) => {
        //     if (e.target.classList.contains('modal')) {
        //         this.hideAddServerModal();
        // }
        // });
    }

    async loadServers() {
        try {
            const response = await fetch('/api/servers');
            const data = await response.json();
            
            if (data.success) {
                this.renderServerList(data.servers);
            } else {
                this.showNotification('加载服务器列表失败', 'error');
            }
        } catch (error) {
            console.error('加载服务器失败:', error);
            this.showNotification('网络错误，无法加载服务器列表', 'error');
        }
    }

    renderServerList(servers) {
        const serverList = document.getElementById('serverList');
        
        if (servers.length === 0) {
            serverList.innerHTML = '<div class="loading">暂无服务器配置</div>';
            return;
        }

        serverList.innerHTML = servers.map(server => `
            <div class="server-item" data-server-name="${server.name}">
                <div class="server-actions">
                    <button class="delete-btn" onclick="sshManager.deleteServer('${server.name}')">删除</button>
                </div>
                <h3>${server.name}</h3>
                <p>${server.ip}:${server.port || 22}</p>
                <p>用户: ${server.username}</p>
                <p>认证: ${server.auth_type === 'password' ? '🔑 密码' : '🔐 密钥'}</p>
                ${server.description ? `<p>描述: ${server.description}</p>` : ''}
            </div>
        `).join('');

        // 绑定服务器选择事件
        serverList.querySelectorAll('.server-item').forEach(item => {
            item.addEventListener('click', (e) => {
                if (!e.target.classList.contains('delete-btn')) {
                    this.selectServer(item.dataset.serverName);
                }
            });
        });
    }

    selectServer(serverName) {
        // 移除之前的选中状态
        document.querySelectorAll('.server-item').forEach(item => {
            item.classList.remove('selected');
        });

        // 添加选中状态
        const selectedItem = document.querySelector(`[data-server-name="${serverName}"]`);
        if (selectedItem) {
            selectedItem.classList.add('selected');
        }

        this.currentServer = serverName;
        this.updateServerInfo(serverName);
        this.enableCommandInput();
    }

    async updateServerInfo(serverName) {
        try {
            const response = await fetch('/api/servers');
            const data = await response.json();
            
            if (data.success) {
                const server = data.servers.find(s => s.name === serverName);
                if (server) {
                    this.renderServerInfo(server);
                }
            }
        } catch (error) {
            console.error('获取服务器信息失败:', error);
        }
    }

    renderServerInfo(server) {
        const serverInfo = document.getElementById('serverInfo');
        serverInfo.innerHTML = `
            <h2>ℹ️ 服务器信息</h2>
            <div class="server-details">
                <p><strong>名称:</strong> ${server.name}</p>
                <p><strong>IP地址:</strong> ${server.ip}</p>
                <p><strong>端口:</strong> ${server.port || 22}</p>
                <p><strong>用户名:</strong> ${server.username}</p>
                <p><strong>认证方式:</strong> ${server.auth_type === 'password' ? '🔑 密码' : '🔐 SSH密钥'}</p>
                ${server.description ? `<p><strong>描述:</strong> ${server.description}</p>` : ''}
            </div>
        `;
    }

    enableCommandInput() {
        document.getElementById('commandInput').disabled = false;
        document.getElementById('executeBtn').disabled = false;
        document.getElementById('testConnectionBtn').disabled = false;
    }

    showAddServerModal() {
        document.getElementById('addServerModal').style.display = 'block';
        document.getElementById('addServerForm').reset();
        this.toggleAuthFields('password');
    }

    hideAddServerModal() {
        document.getElementById('addServerModal').style.display = 'none';
    }

    toggleAuthFields(authType) {
        const passwordGroup = document.getElementById('passwordGroup');
        const keyPathGroup = document.getElementById('keyPathGroup');
        
        if (authType === 'password') {
            passwordGroup.style.display = 'block';
            keyPathGroup.style.display = 'none';
            document.getElementById('password').required = true;
            document.getElementById('keyPath').required = false;
        } else {
            passwordGroup.style.display = 'none';
            keyPathGroup.style.display = 'block';
            document.getElementById('password').required = false;
            document.getElementById('keyPath').required = true;
        }
    }

    async addServer() {
        const formData = new FormData(document.getElementById('addServerForm'));
        const serverData = {
            name: formData.get('serverName'),
            ip: formData.get('serverIp'),
            port: parseInt(formData.get('serverPort')) || 22,
            username: formData.get('username'),
            auth_type: formData.get('authType'),
            description: formData.get('description')
        };

        if (serverData.auth_type === 'password') {
            serverData.password = formData.get('password');
        } else {
            serverData.key_path = formData.get('keyPath');
        }

        try {
            const response = await fetch('/api/servers', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(serverData)
            });

            const result = await response.json();
            
            if (result.success) {
                this.showNotification(result.message, 'success');
                this.hideAddServerModal();
                this.loadServers();
            } else {
                this.showNotification(result.message, 'error');
            }
        } catch (error) {
            console.error('添加服务器失败:', error);
            this.showNotification('网络错误，无法添加服务器', 'error');
        }
    }

    async deleteServer(serverName) {
        if (!confirm(`确定要删除服务器 "${serverName}" 吗？`)) {
            return;
        }

        try {
            const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            
            if (result.success) {
                this.showNotification(result.message, 'success');
                if (this.currentServer === serverName) {
                    this.currentServer = null;
                    this.clearServerInfo();
                    this.disableCommandInput();
                }
                this.loadServers();
            } else {
                this.showNotification(result.message, 'error');
            }
        } catch (error) {
            console.error('删除服务器失败:', error);
            this.showNotification('网络错误，无法删除服务器', 'error');
        }
    }

    async executeCommand() {
        if (!this.currentServer) {
            this.showNotification('请先选择一个服务器', 'error');
            return;
        }

        const command = document.getElementById('commandInput').value.trim();
        if (!command) {
            this.showNotification('请输入要执行的命令', 'error');
            return;
        }

        try {
            this.appendOutput(`🚀 正在执行命令: ${command}\n`);
            
            const response = await fetch('/api/execute-command', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    server_name: this.currentServer,
                    command: command
                })
            });

            const result = await response.json();
            
            if (result.success) {
                this.appendOutput(`✅ 命令执行成功\n`);
                if (result.output) {
                    this.appendOutput(`📤 输出:\n${result.output}\n`);
                }
                if (result.error) {
                    this.appendOutput(`⚠️ 错误:\n${result.error}\n`);
                }
            } else {
                this.appendOutput(`❌ 命令执行失败: ${result.error}\n`);
            }
            
            this.appendOutput('─'.repeat(50) + '\n');
            
        } catch (error) {
            console.error('执行命令失败:', error);
            this.appendOutput(`❌ 网络错误: ${error.message}\n`);
            this.appendOutput('─'.repeat(50) + '\n');
        }

        // 清空命令输入
        document.getElementById('commandInput').value = '';
    }

    async testConnection() {
        if (!this.currentServer) {
            this.showNotification('请先选择一个服务器', 'error');
            return;
        }

        try {
            this.appendOutput(`🔗 正在测试与 ${this.currentServer} 的连接...\n`);
            
            const response = await fetch('/api/test-connection', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    server_name: this.currentServer
                })
            });

            const result = await response.json();
            
            if (result.success) {
                this.appendOutput(`✅ ${result.message}\n`);
            } else {
                this.appendOutput(`❌ ${result.error}\n`);
            }
            
            this.appendOutput('─'.repeat(50) + '\n');
            
        } catch (error) {
            console.error('测试连接失败:', error);
            this.appendOutput(`❌ 网络错误: ${error.message}\n`);
            this.appendOutput('─'.repeat(50) + '\n');
        }
    }

    appendOutput(text) {
        const outputContent = document.getElementById('outputContent');
        outputContent.textContent += text;
        outputContent.scrollTop = outputContent.scrollHeight;
    }

    clearOutput() {
        document.getElementById('outputContent').textContent = '';
    }

    clearServerInfo() {
        document.getElementById('serverInfo').innerHTML = `
            <h2>ℹ️ 服务器信息</h2>
            <div class="no-server-selected">请从左侧选择一个服务器</div>
        `;
    }

    disableCommandInput() {
        document.getElementById('commandInput').disabled = true;
        document.getElementById('executeBtn').disabled = true;
        document.getElementById('testConnectionBtn').disabled = true;
    }

    showNotification(message, type = 'info') {
        const notification = document.getElementById('notification');
        notification.textContent = message;
        notification.className = `notification ${type} show`;
        
        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    }
}

// 初始化应用
let sshManager;
document.addEventListener('DOMContentLoaded', () => {
    sshManager = new SSHManager();
}); 